using SqlSugar;
using System.Security.Cryptography;
using System.Text;

namespace HtERP.Services
{
    public class UserService
    {
        private readonly ISqlSugarClient _db;
        private readonly ILogger _logger;
        private readonly IConfiguration _configuration;
        
        public UserService(ISqlSugarClient db, ILogger logger, IConfiguration configuration)
        {
            _db = db;
            _logger = logger;
            _configuration = configuration;
        }
        
        // 获取所有用户
        public async Task<List<Data.User>> GetAllUsersAsync()
        {
            return await _db.Queryable<Data.User>().ToListAsync();
        }
        
        // 根据ID获取用户
        public async Task<Data.User?> GetUserByIdAsync(Guid id)
        {
            return await _db.Queryable<Data.User>().FirstAsync(u => u.Id == id);
        }
        
        // 根据用户名获取用户
        public async Task<Data.User?> GetUserByUsernameAsync(string username)
        {
            return await _db.Queryable<Data.User>().FirstAsync(u => u.Username == username);
        }
        
        // 创建用户
        public async Task<Data.User> CreateUserAsync(string username, string password, string? email = null)
        {
            // 检查用户名是否已存在
            var existingUser = await GetUserByUsernameAsync(username);
            if (existingUser != null)
            {
                throw new ArgumentException("用户名已存在");
            }
            
            var user = new Data.User
            {
                Id = Guid.NewGuid(),
                Username = username,
                PasswordHash = HashPassword(password),
                Email = email,
                IsActive = true,
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now
            };
            
            await _db.Insertable(user).ExecuteCommandAsync();
            _logger.Log(LogLevel.Info, $"创建了新用户: {username}");
            
            return user;
        }
        
        // 更新用户
        public async Task UpdateUserAsync(Data.User user)
        {
            user.UpdatedAt = DateTime.Now;
            await _db.Updateable(user).ExecuteCommandAsync();
            _logger.Log(LogLevel.Info, $"更新了用户信息: {user.Username}");
        }
        
        // 删除用户
        public async Task DeleteUserAsync(Guid id)
        {
            await _db.Deleteable<Data.User>().Where(u => u.Id == id).ExecuteCommandAsync();
            _logger.Log(LogLevel.Info, $"删除了用户: {id}");
        }
        
        // 验证用户凭据
        public async Task<Data.User?> ValidateUserCredentialsAsync(string username, string password)
        {
            // 仅从数据库验证用户，不允许使用配置文件中的WebAPI凭据
            var user = await GetUserByUsernameAsync(username);
            if (user != null && user.IsActive && VerifyPassword(password, user.PasswordHash))
            {
                _logger.Log(LogLevel.Info, $"用户 {username} 数据库验证成功");
                return user;
            }
            
            _logger.Log(LogLevel.Warning, $"用户 {username} 验证失败");
            return null;
        }
        
        // 更改密码
        public async Task ChangePasswordAsync(Guid userId, string currentPassword, string newPassword)
        {
            var user = await GetUserByIdAsync(userId);
            if (user == null)
            {
                throw new ArgumentException("用户不存在");
            }
            
            if (!VerifyPassword(currentPassword, user.PasswordHash))
            {
                throw new ArgumentException("当前密码不正确");
            }
            
            user.PasswordHash = HashPassword(newPassword);
            user.UpdatedAt = DateTime.Now;
            await UpdateUserAsync(user);
            
            _logger.Log(LogLevel.Info, $"用户 {user.Username} 更改了密码");
        }
        
        // 启用/禁用用户
        public async Task ToggleUserStatusAsync(Guid userId)
        {
            var user = await GetUserByIdAsync(userId);
            if (user == null)
            {
                throw new ArgumentException("用户不存在");
            }
            
            user.IsActive = !user.IsActive;
            user.UpdatedAt = DateTime.Now;
            await UpdateUserAsync(user);
            
            _logger.Log(LogLevel.Info, $"{(user.IsActive ? "启用" : "禁用")}了用户: {user.Username}");
        }
        
        // 密码哈希函数
        private string HashPassword(string password)
        {
            using (var sha256 = SHA256.Create())
            {
                var hashedBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(password));
                return Convert.ToBase64String(hashedBytes);
            }
        }
        
        // 密码验证函数
        private bool VerifyPassword(string password, string storedHash)
        {
            var hash = HashPassword(password);
            return hash == storedHash;
        }
    }
}